package cn.lilyssh.common.exception;

import cn.lilyssh.common.result.Result;
import cn.lilyssh.common.result.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;


/**
 * 异常处理
 */
@Slf4j
@ControllerAdvice
public class ExceptionAdviceHandler {
    @ResponseBody
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Throwable.class)
    public Result defaultErrorHandler(Exception e){
        Result result = Result.code(ReturnCode.EXCEPTION);
        if(e instanceof MethodArgumentNotValidException){
            List<ObjectError> objectErrorList = ((MethodArgumentNotValidException)e).getBindingResult().getAllErrors();
            if(!CollectionUtils.isEmpty(objectErrorList)){
                ObjectError objectError = objectErrorList.get(0);
                if(objectError instanceof FieldError){
                    FieldError fieldError = (FieldError) objectError;
                    String message = "[" + fieldError.getField() + "]" + fieldError.getDefaultMessage();
                    result.setMessage(message);
                    log.error(message,e);
                }
            }
        } else {
            log.error("处理出现异常",e);
        }
        return result;
    }
}
